#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2019/4/8
# @Author    :Tian Maohong
# @Email     :tianmaohong@bbdservice.com
# @File      :R37_EC_UpaidExternalGuaranteeBadAmtCheck
# @Software  :PyCharm

'''eof
name:申请企业未结清对外担保业务余额校验（不良类）
code:R37_EC_UpaidExternalGuaranteeBadAmtCheck_2D
tableName:
columnName:
groups:企业征信校验
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import datetime


reload(sys)
sys.setdefaultencoding('utf-8')


def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = EC_DSJ_2D["data"].get(table_Name)
        if data is None:
            return None
        elif data == "" or (isinstance(data, list) and len(data) == 0):
            return [{}]
        else:
            return data
    except:
        return None

def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """

    return_data = None
    data_value = str(data_value)
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                    except:
                        return_data = None

    return return_data

def upaidExternalGuaranteeBadAmtCheck():
    """
    "Factor1=相关还款责任汇总信息·借贷交易相关还款责任汇总信息段(EB05A)-借贷交易相关还款责任汇总信息(EB05AH)·责任类型(EB05AD01)∈(1(个人信贷交易共同还款人/共同债务人),2(保证人),9(其他))·count(其他借贷交易账户不良类类余额(EB05AJ06)>0)
    Factor2=相关还款责任汇总信息·担保交易相关还款责任汇总信息段(EB05B)·责任类型(EB05BD01)∈(1(个人担保交易的共同债务人),2(反担保人),9(其他),0(合计))·count(不良类余额(EB05BJ04)>0)
    Factor3=统计符合相关还款责任借贷账户（不含贴现）信息单元(ED07)·主借款人身份类别(ED070D01)∈(1(自然人),2(组织机构)) and 相关还款责任类型(ED070D03) ∈(1(个人信贷交易共同还款人),2(保证人),3(票据承兑人),4(应收账款债务人),5(供应链核心企业),9(其他))and 五级分类(ED070D08)∈(3(次级),4(可疑),5(损失),6(违约))的笔数；
    Factor4=统计相关还款责任担保账户分机构汇总信息单元(ED09)·相关还款责任类型(ED090D01)∈(1(个人担保交易的共同债务人),2(反担保人),9(其他)) and 五级分类(ED090D04)∈(3(次级),4(可疑),5(损失),6(违约))的笔数
    FACTOR = MAX(FACTOR1,FACTOR2,FACTOR3,FACTOR4)"

    :return:
    """

    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    EB05AD01List = ['1', '2', '9']              # 责任类型(EB05AD01)∈(1(个人信贷交易共同还款人 / 共同债务人), 2(保证人), 9(其他))
    EB05BD01List = ['1', '2', '9', '0']         # 责任类型(EB05BD01)∈(1(个人担保交易的共同债务人),2(反担保人),9(其他),0(合计)
    ED070D01List = ['1', '2']                   # 主借款人身份类别(ED070D01)∈(1(自然人),2(组织机构))
    ED070D03List = ['1','2','3','4','5','9']    # 相关还款责任类型(ED070D03)为1(个人信贷交易共同还款人),2(保证人), 3(票据承兑人),4(应收账款债务人),5(供应链核心企业),9(其他)
    ED070D08List = ['3','4','5','6']            # 五级分类(ED070D08)∈(3(次级),4(可疑),5(损失),6(违约)
    ED090D01List = ['1', '2', '9']              # 相关还款责任类型(ED090D01)∈(1(个人担保交易的共同债务人),2(反担保人),9(其他))
    ED090D04List = ['3', '4','5','6']           # 五级分类(ED090D04)∈(3(次级),4(可疑),5(损失),6(违约))

    # 相关还款责任汇总信息
    EBE = formatData("EBE")
    # 相关还款责任信息
    EDD = formatData("EDD")

    # Factor1
    if EBE is None:
        Factor1 = None
    elif EBE == [{}]:
        Factor1 =  0
    else:
        EB05 = EBE[0].get("EB05")
        if EB05 is None or EB05 == "":
            Factor1 = 0
        else:
            EB05A = EB05[0].get("EB05A")
            if EB05A is None:
                Factor1 = 0
            else:
                EB05AH = EB05A[0].get("EB05AH")
                if EB05AH is None:
                    Factor1 = 0
                else:
                    Factor1 = 0
                    flag = False
                    # EB05AD01List = ['1', '2', '9']
                    for i in range(len(EB05AH)):
                        EB05AD01 = EB05AH[i].get("EB05AD01")        # 责任类型
                        EB05AJ06 = EB05AH[i].get("EB05AJ06")        # 其他借贷交易账户不良类类余额
                        if EB05AD01 in null_type_list or  EB05AJ06 in null_type_list:
                            pass
                        else:
                            flag = True
                            if convertDataType(EB05AD01, 'str') in EB05AD01List and \
                                    isFloat(EB05AJ06) and convertDataType(EB05AJ06, 'float') > 0:
                                Factor1 = Factor1 + 1
                            else:
                                pass
                    if not flag:
                        Factor1 = None

    # Factor2
    if EBE is None:
        Factor2 = None
    elif EBE == [{}]:
        Factor2 = 0
    else:
        EB05 = EBE[0].get("EB05")
        if EB05 is None or EB05 == "":
            Factor2 = 0
        else:
            EB05B = EB05[0].get("EB05B")
            if EB05B is None or EB05B == "":
                Factor2 = 0
            else:
                EB05BH = EB05B[0].get("EB05BH")
                if EB05BH is None:
                    Factor2 = 0
                else:
                    # EB05BD01List = ['1', '2', '9', '0']
                    flag = False
                    Factor2 = 0
                    for i in range(len(EB05BH)):
                        EB05BD01 = EB05BH[i].get("EB05BD01")     # 责任类型
                        EB05BJ04 = EB05BH[i].get("EB05BJ04")     # 不良类余额
                        if EB05BD01 in null_type_list or EB05BJ04 in null_type_list:
                            pass
                        else:
                            flag = True
                            if convertDataType(EB05BD01, 'str') in EB05BD01List and \
                                    isFloat(EB05BJ04) and convertDataType(EB05BJ04, 'float') > 0:
                                Factor2 = Factor2 + 1
                            else:
                                pass
                    if not flag:
                        Factor2 = None

    # Factor3
    if EDD is None:
        Factor3 = None
    elif EDD == [{}]:
        Factor3 = 0
    else:
        ED07 = EDD[0].get("ED07")
        if ED07 is None:
            Factor3 = 0
        else:
            flag = False
            Factor3 = 0
            for i in range(len(ED07)):
                ED070D01 = ED07[i].get("ED070D01")
                ED070D03 = ED07[i].get("ED070D03")
                ED070D08 = ED07[i].get("ED070D08")
                if ED070D03 in null_type_list or ED070D01 in null_type_list or ED070D08 in null_type_list:
                    pass
                else:
                    flag = True
                    if convertDataType(ED070D01, 'str') in ED070D01List and \
                            convertDataType(ED070D03, 'str') in ED070D03List and \
                            convertDataType(ED070D08, 'str') in ED070D08List:
                        Factor3 = Factor3 + 1
            if not flag:
                Factor3 = None

    # Factor4
    if EDD is None:
        Factor4 = None
    elif EDD == [{}]:
        Factor4 = 0
    else:
        ED09 = EDD[0].get("ED09")
        if ED09 is None:
            Factor4 = 0
        else:
            Factor4 = 0
            flag = False
            for i in range(len(ED09)):
                ED090D01 = ED09[i].get("ED090D01")      # 相关还款责任类型
                ED090D04 = ED09[i].get("ED090D04")      # 五级分类
                if ED090D01 in null_type_list or ED090D04 in null_type_list:
                    pass
                else:
                    flag = True
                    if convertDataType(ED090D01, 'str') in ED090D01List and \
                            convertDataType(ED090D04, 'str') in ED090D04List:
                        Factor4 = Factor4 + 1
                    else:
                        pass
            if not flag:
                Factor4 = None

    if Factor1 is None and Factor2 is None and Factor3 is None and Factor4 is None:
        return u'缺失值'
    else:
        if Factor1 is None:
            Factor1 = 0
        if Factor2 is None:
            Factor2 = 0
        if Factor3 is None:
            Factor3 = 0
        if Factor4 is None:
            Factor4 = 0
        # Factor
        Factor = max(Factor4, Factor3, Factor2, Factor1)

        return Factor

result = upaidExternalGuaranteeBadAmtCheck()


